<template>
  <br/>

  <CellGroup inset  v-if="isStart">
    <Field name="slider" label="抢单进度">
      <template #input>
        <Circle  v-model:current-rate="currentRate"
                 :rate="rateVal"
                 :speed="100"
                 :text="text"/>
      </template>
    </Field>
    <Field name="slider"
           v-model="taskResult.taskSign"
           label="任务标志"
           disabled>
    </Field>
    <Field name="slider"
           v-model="taskResult.successCount"
           label="本次抢单量"
           disabled/>
    <Field name="slider"
           v-model="taskResult.stopValidate"
           label="异常"
           disabled>
    </Field>




  </CellGroup>
  <CellGroup inset v-else >
    <Field name="stepper" label="频率">
      <template #input>
        <Stepper v-model="frequency" min="2" max="6" integer />
      </template>
    </Field>
    <Field name="stepper" label="抢单量">
      <template #input>
        <Stepper v-model="orderCount" min="1" max="10" integer />
      </template>
    </Field>
    <Field name="slider" label="分数（底限）">
      <template #input>
        <Stepper v-model="scopeLimit" min="100" max="1000" step="100" integer />
      </template>
    </Field>
  </CellGroup>
    <br/>
    <br/>
<!--  BUTTON  -->
    <div style="margin: 16px;">
      <Button type="warning" round @click="closeAK"  block :disabled="stopButton"> 停止抢单 </Button>
    </div>
    <div style="margin: 16px;">
      <Button type="default" round @click="getAkTaskByTaskId"  block :disabled="ready">检查状态</Button>
    </div>
    <div style="margin: 16px;">
      <Button round block type="primary" @click="startAK"  :disabled="startButton">
        开始任务
      </Button>
    </div>

  <br/>
  <br/>

</template>

<script setup name="Work">
import {Button, Col, Row, Slider, Circle, Stepper, Form, Field, CellGroup, Notify, Dialog} from "vant";
import {computed, isReactive, onMounted, reactive, ref, watch} from "vue";
import { messageTip} from "@/utils/messageTip";
import {doGet, doPost} from "@/utils/request";
import {getToken, removeToken} from "@/utils/auth";
import router from "@/router";
let frequency = ref(5)
let orderCount = ref(1)
let scopeLimit = ref(500)
let rateVal = computed(() =>{
  return taskResult.successCount / orderCount.value * 100
})
let taskId
let isStart = ref(false)
let startButton = ref(false)
let stopButton = ref(true)
let pageValid = true
let ready = ref(false)


let timeoutId
let startFlag = false

let taskResult = reactive({
  taskSign: "",
  successCount:0,
  stopValidate:""
});
let orderInfo = null;
const currentRate = ref(0);
const text = computed(() => currentRate.value.toFixed(0) + '%');

async function startAK(){
  if (startFlag){
    return
  }
  startFlag = true
  await pageValidCheck()
  if (!pageValid){
    messageTip("页面已经失效，即将跳转登录页！",  "danger")
    setTimeout(()=>{
      removeToken()
      router.push("/login")
    }, 2000)
    return;
  }
   orderInfo.orderCount = orderCount.value
   orderInfo.scopeLimit = scopeLimit.value
   orderInfo.cron = "0/" + frequency.value + " * * * * ?"
   doPost("/creatTask", orderInfo).then(req =>{
     if (req.data.code == 200){
       messageTip("抢单任务开始，请留意邮箱!", "success")
       startButton.value = true
       stopButton.value = false
       isStart.value = true
       startFlag = false
       ready.value = true
       //延迟开启
       setTimeout(()=>{
         ready.value = false
       },frequency.value * 1000)
     }else if (req.data.code == 333) {
       messageTip(req.data.msg, "danger")
       removeToken();
       window.location.href = "/login"
     }else {
       messageTip(req.data.msg, "danger")
       startFlag = false
     }
   }).catch(() =>{
     messageTip("未知错误，请重新登录！",  "error")
     removeToken();
   })
}
function closeAK(){
  if (taskId === null){
    messageTip("请重新登录",  "error")
    return
  }
  Dialog.confirm({
        message: '确认关闭抢单？'
      }

  ).then(() => {
    doGet("/cancelTask", {"taskId": taskId}).then(req =>{
      if (req.data.code == 200){
        messageTip("已经成功关闭抢单！", "success")
        startButton.value = false
        stopButton.value = true
        isStart.value = false
      }else if (req.data.code == 333){
        messageTip(req.data.msg, "danger")
        removeToken()
        router.push("/login")
      }else {
        messageTip(req.data.msg, "danger")
      }
    })
  })
  .catch(() => {
    messageTip("已取消", "success")
  })
}
function getAkTaskByTaskId(){
  doGet("/getTaskByTaskId",{"taskId": taskId}).then(res =>{
    if (res.data.code === 200){
      if (res.data.o == null){
        messageTip("未开启任务！（若开始抢单后查不到任务请重新登录！）", "warning")
      }else {
        //判断后台当前任务是否执行
        if (res.data.o.stopValidate){
          messageTip(res.data.o.stopValidate + "抢单量：  " + res.data.o.successCount, "warning")
          initState()
          isStart.value = false
        }else {
          taskResult.taskSign = res.data.o.taskSign
          taskResult.successCount =res.data.o.successCount
          taskResult.stopValidate = res.data.o.stopValidate
          startButton.value = true;
          stopButton.value = false;
          isStart.value = true
        }


      }
    }else {
      messageTip(res.data.msg, "danger")
    }
  })
}
function checkTask(){
   doGet("/getTaskByTaskId",{"taskId": taskId}).then(res =>{
    if (res.data.code === 200){
      if (res.data.o === null){
        //未登录
        startButton.value = true;
        stopButton.value = true;
        pageValid = false;
        messageTip("非法的请求,请去登录！", "danger")
        removeToken()
        router.push("/login")
        return;
      }
      let taskSign = res.data.o.taskSign;
      let stopValidate = res.data.o.stopValidate;
      if (taskSign === null){
        //未登录
        startButton.value = true;
        stopButton.value = true;
        pageValid = false;
        messageTip("非法的请求,请去登录！", "danger")
        removeToken()
        router.push("/login")
        return;
      }
      if (taskSign != orderInfo.userKey){
        startButton.value = true;
        stopButton.value = true;
        pageValid = false;
        messageTip("已在其他地方登录！当前页面已经失效！","warning")
        removeToken()
      }else{
        //属于当前会话的查询 关闭还是正常
        if (stopValidate == null){
          //任务开启中
          startButton.value = true;
          stopButton.value = false;
          isStart.value = true
        }else {
          //被关闭
          startButton.value = false;
          stopButton.value = true;
          isStart.value = false
        }
      }
    }
  })
}
function pageValidCheck(){
  return doGet("/getTaskByTaskId",{"taskId": taskId}).then(res => {
    if (res.data.code === 200) {
      if (res.data.o === null) {
        //未登录
        startButton.value = true;
        stopButton.value = true;
        pageValid = false;
        messageTip("非法的请求,请去登录！", "danger")
        return;
      }
      let taskSign = res.data.o.taskSign;
      let stopValidate = res.data.o.stopValidate;
      if (taskSign === null) {
        //未登录
        startButton.value = true;
        stopButton.value = true;
        pageValid = false;
        messageTip("非法的请求,请去登录！", "danger")
        return;
      }
      if (taskSign != orderInfo.userKey) {
        startButton.value = true;
        stopButton.value = true;
        pageValid = false;
        messageTip("已在其他地方登录！当前页面已经失效！", "warning")
        return;
      }
    }
  })
}
watch(()=>{return taskResult.stopValidate}, (newVal) =>{
  if (newVal){
    //按钮初始化
    initState()
  }
})

function initState(){
  isStart.value = false
  startButton.value = false
  stopButton.value = true
}
onMounted(() =>{
  orderInfo =getToken();
  if (orderInfo === null) {
    messageTip("非法的请求,请去登录！", "danger")
    router.push("/login")
    return;
  }
  taskId = orderInfo.userAccount;
  checkTask();
})
</script>

<style>
</style>